<!--

-->
<template>
  <div class="page-login">

    <el-form class="form-box" ref="ruleForm" :model="submitForm" :rules="formRule">
      <el-form-item prop="username">
        <el-input v-model="submitForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="submitForm.password" placeholder="请输入密码" show-password prefix-icon="el-icon-lock" />
      </el-form-item>
      <el-button type="primary" @click="handleLogin(ruleForm)">登录</el-button>
    </el-form>

  </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElLoading, ElMessage } from 'element-plus'
import { throttle } from '@/utils'
import { setToken } from '@/utils/auth'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单实例
const ruleForm = ref<FormInstance>()

// 表单数据
const submitForm = reactive({
  username: '',
  password: ''
})

// 校验规则
const formRule = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
})

// 登录方法
const handleLogin = throttle((formEl: FormInstance | undefined) => {

  if (!formEl) return

  formEl.validate((valid,) => {

    // 校验不通过
    if (!valid) {
      return
    }

    // 校验通过
    const loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    new Promise<any>((resolve) => {
      setTimeout(() => {
        resolve({
          code: 0,
          data: Math.random().toString().replace('0.', ''),
        })
      }, 1000)
    }).then(res => {
      if (res.code === 0) {
        setToken(res.data)
        ElMessage.success('登录成功')
        router.replace('/one/one')
      } else {
        ElMessage.warning(res.msg)
      }
    }).finally(() => {
      loading.close()
    })

  })

})

</script>

<style lang='scss' scoped>
.page-login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .form-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px;
    border-radius: 20px;
    box-shadow: 0px 0px 10px #3f9dff;
    background-color: rgba(0, 0, 0, 0.6);

    .el-form-item {
      width: 100%;
    }
  }
}
</style>